package com.hmall.order.web;

import com.hmall.order.dto.OrderRequest;
import com.hmall.order.pojo.Order;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

   @Autowired
   private IOrderService orderService;

   @Autowired
   private RabbitTemplate rabbitTemplate;

   @GetMapping("/{id}")
   public Order queryOrderById(@PathVariable("id") Long orderId) {
      return orderService.getById(orderId);
   }

   @PostMapping
   public Long createOrder(@RequestBody OrderRequest params) {
      log.info("params:{}",params);
      Long id = orderService.createOrderAbout(params);

      Message message = MessageBuilder.withBody(id.toString().getBytes(StandardCharsets.UTF_8))
              //.setExpiration("20000")
              .setHeader("x-delay",30000)
              // .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
              .build();
      CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
      rabbitTemplate.convertAndSend("delay.direct","delay",message,correlationData);
      log.info("order message sent successfully !!!");
      return id;
   }
}
